package init_matrix

import (
	"fmt"
	"image"
	"sync"
)

type Point struct {
	DX float64
	DY float64
}

func (p Point) DistanceSqu(addx, addy float64) float64 {
	return (p.DX+addx)*(p.DX+addx) + (p.DY+addy)*(p.DY+addy)
}

var wg1 sync.WaitGroup
var wg2 sync.WaitGroup

// GetPhotoMask 获取灰度图遮罩数据
func GetPhotoMask(img image.Image, length, width int, weight float64) (photoMask [][]bool, err error) {
	if weight < 0 || weight > 1 {
		return nil, fmt.Errorf("weight must between 0 and 1")
	}

	photoMask = make([][]bool, width)
	compare := uint32(32767 * weight)

	for i := 0; i < width; i++ {
		wg1.Add(1)
		go func(img image.Image, length, lineIdx int, compare uint32) {
			defer wg1.Done()
			maskArray := traversalArray(img, length, lineIdx, compare)
			photoMask[lineIdx] = maskArray
		}(img, length, i, compare)
	}
	wg1.Wait()
	return
}

// 遍历图片
func traversalArray(img image.Image, length, lineIdx int, compare uint32) []bool {
	lineMasks := make([]bool, 0, length)
	for j := 0; j < length; j++ {
		if r, _, _, _ := img.At(j, lineIdx).RGBA(); r <= compare {
			lineMasks = append(lineMasks, false)
		} else {
			lineMasks = append(lineMasks, true)
		}
	}
	return lineMasks
}

func InitMatrix(length, width int) (m [][]*Point) {
	m = make([][]*Point, width)
	for i := 0; i < width; i++ {
		wg2.Add(1)
		go func(i int) {
			defer wg2.Done()
			temp := make([]*Point, 0, length)
			for j := 0; j < length; j++ {
				temp = append(temp, &Point{})
			}
			m[i] = temp
		}(i)
	}
	wg2.Wait()
	return
}
